<template>
  <div v-if="!hasUserInfo">
    <div v-if="showBtn" class="div-pop" catchtouchmove="true">      
      <div class="get-user-info">
        <img v-if="fileSpace" class="width-375 height-147 top-info-bg" :src="fileSpace + '/images/w-login-bg.jpg'"/>
        <div class="top-nav" :style="'height: '+ spaceBarHeight + 'px; padding-top: '+ statusBarTop + 'px;'">
          <div class="flex-center v-align-c">
            <!-- <span class="back-btn" v-if="showBackBtn" @click="backPage"></span> -->
            <label class="top-txt">登录</label>
          </div>
        </div>
        <div class="align-c pad-l-30 pad-r-30 mar-l-15 mar-r-15">
          <div class="width-95 height-95 pic-bar">
            <img class="width-95 height-95" v-if="appInfo.appLogo" :src="appInfo.appLogo"/>
          </div>
          <div class="top-info-circle"></div>
          <div class="info-content">
            <div class="font-17 mar-t-15 mar-b-6 title-1">授权登录</div>
            <div class="font-15 info-des">
              <p>为保障陛下您的体验旅程</p>
              <p>请先登录一下~</p>
            </div>
            <div class="width-230">
              <button v-if="canIUseGetUserProfile" size="default" class="primary-button font-17" @tap="bindGetUserProfile">
                微信登录
              </button>
              <button v-else size="default" class="primary-button font-17" open-type="getUserInfo" lang="zh_CN" @getuserinfo="bindGetUserInfo">
                微信登录
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import { getMemberInfo, updateMember } from '@/api/home'
  import { checkPayMethod, createMemberForAllinpay } from '@/api/pay'
  import { decrypt } from '@/api/wechat'
  import { checkLogin } from '@/api/login'
  import { setVeekrayStatus, setCustomerId, setPayMethod } from '@/utils/auth'

  export default {
    data() {
      return {
        isComponents: true,
        userInfo: {},
        hasUserInfo: false,
        showBtn: false,
        spaceBarHeight: 0,
        statusBarTop: 0,
        appInfo: {},
        canIUseGetUserProfile: false
      }
    },
    props: {
      showBackBtn: {
        type: Boolean,
        default: false
      }
    },
    onLoad() {
      // 初始化data
      Object.assign(this.$data, this.$options.data())
      if (this.$pt.getUserProfile) {
        this.canIUseGetUserProfile = true
      }
      this.spaceBarHeight = this.$pt.getSystemInfoSync()['statusBarHeight'] + 44 + 36
      this.statusBarTop = this.$pt.getSystemInfoSync()['statusBarHeight'] + 10
      setTimeout(() => {
        if (this.$pt.getStorageSync('appInfo')) {
          this.appInfo = this.$pt.getStorageSync('appInfo')
        }
      }, 500)
    },
    onShow() {
      this.getMemberInfo()
    },
    mounted() {
      setTimeout(() => {
        this.getMemberInfo()
      }, 100)
    },
    methods: {
      backPage() {
        this.$emit('showPage')
      },
      getMemberInfo() {
        if (!this.getCustomerId) {
          this.showBtn = true
          return false
        }
        // 访客基本信息, 用户已经授权过、登录过，已获取customerId，判断用户信息是否需要重新获取（重新授权）
        getMemberInfo(this.getCustomerId).then((response) => {
          if (response.isError) return
          if (!this.getCustomerId) {
            this.memberInfo.avatar = 'https://veekrayimg.joinsun.vip/head-portrait.png'
          }
          // 如果会员数据还没有更新，就获取会员信息。nickname、avatar两个信息不存在时，发起重新授权
          if (!response.data.nickname || !response.data.avatar) {
            setTimeout(() => {
              console.log('重新授权事件999')
              if (this.canIUseGetUserProfile) {
                this.getGetUserInfo('profile')
                return
              }
              this.getGetUserInfo('info')
            }, 100)
          } else {
            this.hasUserInfo = true
            // 如果顾客已经是付费名片，要及时刷新缓存
            if (response.data.veekrayStatus === 1) {
              setVeekrayStatus(response.data.veekrayStatus)
            }
            if (this.$pt.getStorageSync('homeNone')) {
              this.$emit('updateUserInfo')
              this.$pt.removeStorageSync('homeNone')
            }
          }
        }).catch(() => {
        })
      },
      bindGetUserProfile(e) {
        // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
        // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
        this.$pt.getUserProfile({
          desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
          success: (res) => {
            console.log('bindGetUserProfile', res)
            this.common(res, 'profile')
          }
        })
      },
      bindGetUserInfo(e) {
        const res = e.mp.detail
        if (res) {
          this.common(res, 'info')
        }
      },
      common(resData, type) {
        this.userInfo = resData.userInfo
        // 记录到全局变量中
        this.globalData.userInfo = resData.userInfo
        this.hasUserInfo = true
        this.updateUnionId(resData, type)
        if (this.getVeekrayStatus !== -1) {
          this.doUpdateMember(this.getCustomerId)
        } else {
          if (this.getCustomerId) {
            this.doUpdateMember(this.getCustomerId)
          } else {
            let myId = this.$pt.getStorageSync('myId')
            if (!myId && this.appInfo.defaultMemberId) {
              this.$utils.setMyId(this.appInfo.defaultMemberId)
              this.$pt.reLaunch({ url: '/pages/home/main' })
            }
            let getUserInfo = this.$pt.getStorageSync('getUserInfo')
            if (getUserInfo) {
              switch (getUserInfo.path) {
                case 'pages/home/main':
                  this.$pt.reLaunch({ url: '/pages/home/main' })
                  break
                case 'pages/shop/detail/main':
                  setTimeout(() => {
                    if (getUserInfo.shareMemberId) {
                      this.$pt.reLaunch({
                        url: '/pages/shop/detail/main?memberId=' + getUserInfo.memberId + '&goodsId=' +
                          getUserInfo.goodsId + '&goodsType=' + getUserInfo.goodsType + '&shareMemberId' + getUserInfo.shareMemberId
                      })
                    } else {
                      this.$pt.reLaunch({
                        url: '/pages/shop/detail/main?memberId=' + getUserInfo.memberId + '&goodsId=' +
                          getUserInfo.goodsId + '&goodsType=' + getUserInfo.goodsType + '&shareMemberId='
                      })
                    }
                  }, 800)
                  break
                case 'pages/article/detail/main':
                  setTimeout(() => {
                    this.$pt.reLaunch({
                      url: '/pages/article/detail/main?memberId=' + getUserInfo.memberId + '&articleId=' + getUserInfo.articleId + '&shareArticle=true'
                    })
                  }, 800)
                  break
              }
            } else {
              if (!myId && this.appInfo.defaultMemberId) {
                this.$utils.setMyId(this.appInfo.defaultMemberId)
                this.$pt.reLaunch({ url: '/pages/home/main' })
              }
            }
            setTimeout(() => {
              this.$utils.removeMyId('getUserInfo')
            }, 3500)
          }
        }
      },
      getGetUserInfo(resData, type) {
        if (type === 'profile') {
          console.log('profile type1')
          this.hasUserInfo = true
          this.updateUnionId(resData)
        } else {
          console.log('userInfo type1')
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          this.$pt.getUserInfo({
            success: (res) => {
              this.userInfo = res.userInfo
              this.globalData.userInfo = res.userInfo
              this.hasUserInfo = true
              this.updateUnionId(res)
            }
          })
        }
      },
      doUpdateMember(customerId) {
        if (!customerId) return
        let data = {
          memberId: customerId,
          nickname: this.userInfo.nickName,
          avatar: this.userInfo.avatarUrl
        }
        if (!this.userInfo.nickName) {
          checkLogin(this.getMemberId)
          return
        }
        updateMember(data).then((response) => {
          if (response.isError) return
          this.$pt.removeStorageSync('homeNone')
          this.$emit('updateUserInfo')
          console.log('保存访客信息')
        }).catch(() => {
        })
      },
      updateUnionId(res) {
        if (!res.encryptedData) {
          this.$emit('lowVersion')
          this.$pt.showModal({
            title: '提示',
            content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
          })
          return
        }
        // 保存unionId，同时插入/更新会员信息
        decrypt({
          memberId: this.getCustomerId, // getCustomerId可为空值
          encryptedData: res.encryptedData,
          iv: res.iv,
          type: 2
        }).then((response) => {
          // 执行登录
          this.$utils.removeMyId('getUserInfo')
          if (response.data.customerId) {
            this.checkPayMethod(response.data.customerId)
            setCustomerId(response.data.customerId)
            // 如果没有手机授权 立即跳出手机授权页
            if (this.getCustomerId && !this.getPhone) {
              this.$emit('authPhoneInfo')
            }
          }
          // this.doUpdateMember(response.data.customerId)
          // checkLogin(this.getMemberId)
          console.log('保存unionId')
        }).catch(() => {
        })
      },
      checkPayMethod(customerId) {
        checkPayMethod({
          memberId: customerId
        }).then((response) => {
          if (response.data) {
            setPayMethod(response.data)
            if (response.data === 2) {
              this.createMemberForAllinpay(customerId)
            }
          } else {
            setPayMethod(1)
          }
        }).catch(() => {
        })
      },
      createMemberForAllinpay(customerId) {
        createMemberForAllinpay({
          memberId: customerId
        }).then((response) => {
        }).catch(() => {
        })
      }
    }
  }
</script>

<style scoped lang="less">  
  .get-user-info {
    width: 375px;
    height: calc(100vh);
    background-color: #fff;
    overflow: hidden;
    .top-info-circle{
      position: relative;
      z-index: 106;
      width: 100%;
      height: 20px;
      &:after{
        content: '';
        display: block;
        position: absolute;
        z-index: 107;
        font-size: 0;
        left: 50%;
        top: -60px;
        width: 600px;
        height: 220px;
        margin-left: -300px;
        background: #fff;
        border-radius: 100%;
      }
    }
    .info-content{
      position: relative;
      z-index: 107;
      text-align: center;
    }
    .pic-bar{
      margin-top: 86px;
      border-radius: 100px;
      background: #fff;
      position: relative;
      z-index: 110;
      img{
        border-radius: 100px;
      }
    }
    .title-1{
      color: #292929;
    }
    .info-des{
      text-align: center;
      color: #818181;
    }
    .steps{
      text-align: center;
      color: #818181;
    }
    .primary-button{
      background: linear-gradient(to right, #ff8e4b, #ff4e25);
      color: #fff;
      border-radius: 50px;
      margin-top: 138px;
      padding: 1px 0;
    }
    .top-info-bg{
      position: fixed;
      left: 0;
      top: 0;
      z-index: 100;
    }
    .top-nav{
      // background: #ffffff;
      // color: #333;
      height: 100px;
      padding-top: 29px;
      box-sizing: border-box;
      text-align: center;
      font-size: 15px;
      position: fixed;
      width: 100%;
      left: 0;
      top: 0;
      z-index: 101;
      .top-txt{
        font-size: 18px;
        color: #fff;
      }
      .back-btn{
        width: 24rpx;
        height: 24rpx;
        border-top: 2px solid #fff;
        border-left:2px solid #fff;
        transform: rotate(-45deg);
        position: relative;
        left: -300rpx;
      }
    }
  }
</style>
